package com.wowangz.cms.dailyoperation.store.api;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.google.gson.Gson;
import com.wowangz.cms.common.mongo.MongoDBManager;
import com.wowangz.cms.common.pojo.AjaxDataEntity;
import com.wowangz.cms.common.pojo.DataDictionaryInfo;
import com.wowangz.cms.common.utils.CommonCrypto;
import com.wowangz.cms.common.utils.DataDictionaryManage;
import com.wowangz.cms.common.utils.DictTypeConstant;
import com.wowangz.cms.common.utils.FileTools;
import com.wowangz.cms.common.utils.FreeMarkerResolve;
import com.wowangz.cms.common.utils.MessageObject;
import com.wowangz.cms.common.utils.SysConstant;
import com.wowangz.cms.component.datagrid.pojo.DataGrid;
import com.wowangz.cms.component.datagrid.pojo.DataResult;
import com.wowangz.cms.component.datagrid.pojo.DataStyle;
import com.wowangz.cms.component.datagrid.pojo.PangingParam;
import com.wowangz.cms.component.datagrid.utils.DataTypeConstant;
import com.wowangz.cms.component.datagrid.utils.PangingTools;
import com.wowangz.cms.dailyoperation.store.pojo.AdminUser;
import com.wowangz.cms.dailyoperation.store.pojo.StoreEntity;
import com.wowangz.cms.dailyoperation.store.pojo.StoreRedisInfo;
import com.wowangz.cms.dailyoperation.store.service.StoreService;
import com.wowangz.cms.syscore.IssTransactionContainer;
import com.wowangz.cms.syscore.api.BaseController;
import com.wowangz.cms.syscore.api.JSONFactory;
import com.wowangz.cms.syscore.autotask.pojo.StoreLoginUser;
import com.wowangz.cms.syscore.autotask.service.StoreDatabaseResourceService;
import com.wowangz.cms.syscore.exception.ServiceException;
import com.wowangz.cms.syscore.pojo.RouteInfo;
import com.wowangz.cms.syscore.utils.JedisUtil;
import com.wowangz.cms.syscore.utils.MessageResourcesUtils;
import com.wowangz.cms.syscore.utils.RSAUtils;
import com.wowangz.cms.syscore.utils.ServletUtils;
import com.wowangz.cms.syscore.utils.SystemConfig;
import com.wowangz.cms.systemmanage.city.pojo.City;
import com.wowangz.cms.systemmanage.databaseresource.pojo.DatabaseBinding;
import com.wowangz.cms.systemmanage.databaseresource.pojo.DatabaseResource;
import com.wowangz.cms.systemmanage.databaseresource.service.DatabaseBindingService;
import com.wowangz.cms.systemmanage.email.set.entity.SystemEmail;
import com.wowangz.cms.systemmanage.email.set.service.SystemEmailService;
import com.wowangz.cms.systemmanage.province.pojo.Province;
import com.wowangz.cms.topic.attachment.entity.Attachment;
import com.wowangz.cms.topic.attachment.service.AttachmentService;

@SuppressWarnings("unchecked")
@Scope("prototype")
@Controller
public class StoreController extends BaseController {

	private final Logger logger = LoggerFactory.getLogger(StoreController.class);

	/**
	 * 复核
	 *
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(value = "/dailyoperation/store/approve.web", method = RequestMethod.GET)
	public void approve(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String id = request.getParameter("id");
		String flag = request.getParameter("flag");
		AjaxDataEntity entity = new AjaxDataEntity();
		StoreService storeService = (StoreService) IssTransactionContainer.getInstance(StoreService.class, false);
		try {
			SystemEmail systemEmail = getSystemEmail();
			if (systemEmail != null) {
				if (StringUtils.isNotEmpty(id)) {
					StoreEntity store = storeService.findOne(Long.parseLong(id));
					storeService = (StoreService) IssTransactionContainer.getInstance(StoreService.class, true);
					if (store != null) {
						if (StringUtils.equals(flag, String.valueOf(SysConstant.CommonApproveStatus.OK))) {
							store.setState(SysConstant.CommonApproveStatus.OK);
							storeService.update(store);
							// add by yoyo
							initialization(Long.valueOf(store.getId()));
							userContext.setInfoMessage(MessageResourcesUtils.getMessage(request, "dailyoperattionstore.approval.pass.success"));
							userContext.setCloseWindow(false);
						} else if (StringUtils.equals(flag, String.valueOf(SysConstant.CommonApproveStatus.REFUSED))) {
							store.setState(SysConstant.CommonApproveStatus.REFUSED);
							storeService.update(store);
							userContext.setInfoMessage(MessageResourcesUtils.getMessage(request, "dailyoperattionstore.approval.refused.success"));
						}
					}
				}
			} else {
				String errorMessage = MessageResourcesUtils.getMessage(request, "systemtmanage.user.template.alert");
				getUserContext().setErrorMessage(errorMessage);
			}

		} catch (Exception e) {
			e.printStackTrace();
			if (StringUtils.equals(flag, String.valueOf(SysConstant.CommonApproveStatus.OK))) {
				userContext.setErrorMessage( MessageResourcesUtils.getMessage(request, "dailyoperattionstore.approval.pass.error"));
			} else if (StringUtils.equals(flag, String.valueOf(SysConstant.CommonApproveStatus.REFUSED))) {
				userContext.setErrorMessage( MessageResourcesUtils.getMessage(request, "dailyoperattionstore.approval.refused.error"));
			}
		} finally {
			try {
				userContext.setCloseWindow(false);
				response.getWriter().write(JSONFactory.toJSONString(entity, userContext));
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 跳转到审核页面
	 *
	 * @return
	 */
	@RequestMapping(value = "/dailyoperation/store/approveList.web", method = RequestMethod.GET)
	public String approveList() {
		return "/WEB-INF/jsp/dailyoperation/store/approval";
	}

	/**
	 * 批量审核
	 *
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/dailyoperation/store/batchApprove.web", method = RequestMethod.POST)
	public void batchApprove(HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> map = new HashMap<String, Object>();
		String flag = request.getParameter("flag");
		String ids = request.getParameter("ids");
		try {
			long state = 0l;
			StoreService storeService = (StoreService) IssTransactionContainer.getInstance(StoreService.class, true);
			SystemEmail systemEmail = getSystemEmail();
			if (systemEmail != null) {
				if (StringUtils.isNotEmpty(ids)) {
					String[] idsStrings = ids.split(",");
					for (String string : idsStrings) {
						map = new HashMap<String, Object>();
						map.put("id", Long.valueOf(string));
						if (StringUtils.equals(flag, String.valueOf(SysConstant.CommonApproveStatus.OK))) {
							state = SysConstant.CommonApproveStatus.OK;
							// 设置为启用状态
							map.put("businessstatus", SysConstant.CommonUsedStatus.START);
							map.put("state", state);
							storeService.updateApprove(map);
							initialization(Long.valueOf(string));
						} else {
							state = SysConstant.CommonApproveStatus.REFUSED;
							map.put("state", state);
							storeService.updateApprove(map);
						}
					}
					map = new HashMap<String, Object>();
					map.put("code", "200");
					if (StringUtils.equals(flag, String.valueOf(SysConstant.CommonApproveStatus.OK))) {
						map.put("message", MessageResourcesUtils.getMessage(request, "dailyoperattionstore.approval.pass.success"));
					} else {
						map.put("message", MessageResourcesUtils.getMessage(request, "dailyoperattionstore.approval.refused.success"));
					}
				}
			} else {
				map.put("code", "400");
				String errorMessage = MessageResourcesUtils.getMessage(request, "systemtmanage.user.template.alert");
				map.put("message", errorMessage);
			}
		} catch (Exception e) {
			map.put("code", "400");
			if (StringUtils.equals(flag, String.valueOf(SysConstant.CommonApproveStatus.OK))) {
				map.put("message", MessageResourcesUtils.getMessage(request, "dailyoperattionstore.approval.pass.error"));
			} else {
				map.put("message", MessageResourcesUtils.getMessage(request, "dailyoperattionstore.approval.refused.error"));
			}
			e.printStackTrace();
		} finally {
			try {
				response.getWriter().write(new Gson().toJson(map));
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 批量启用停用
	 *
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/dailyoperation/store/batchStartOrStop.web", method = RequestMethod.POST)
	public void batchStartOrStop(HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> map = new HashMap<String, Object>();
		String flag = request.getParameter("flag");
		try {
			String ids = request.getParameter("ids");
			long businessstatus = 0l;
			if (StringUtils.equals(flag, String.valueOf(SysConstant.CommonUsedStatus.STOP))) {
				businessstatus = SysConstant.CommonUsedStatus.STOP;
			} else {
				businessstatus = SysConstant.CommonUsedStatus.START;
			}
			StoreService storeService = (StoreService) IssTransactionContainer.getInstance(StoreService.class, true);
			if (StringUtils.isNotEmpty(ids)) {
				String[] idsStrings = ids.split(",");
				for (String string : idsStrings) {
					map = new HashMap<String, Object>();
					map.put("id", Long.valueOf(string));
					map.put("businessstatus", businessstatus);
					storeService.updateApprove(map);
					// add by yoyo 同步商户状态至redis
					syncStroeInfoToRedis(Long.valueOf(string));
				}
				map = new HashMap<String, Object>();
				map.put("code", "200");
				if (StringUtils.equals(flag, String.valueOf(SysConstant.CommonUsedStatus.STOP))) {
					map.put("message",
							MessageResourcesUtils.getMessage(request, "dailyoperattionstore.common.useage.info3"));
				} else {
					map.put("message",
							MessageResourcesUtils.getMessage(request, "dailyoperattionstore.common.useage.info1"));
				}
			}
		} catch (Exception e) {
			map.put("code", "400");
			if (StringUtils.equals(flag, String.valueOf(SysConstant.CommonUsedStatus.STOP))) {
				map.put("message",
						MessageResourcesUtils.getMessage(request, "dailyoperattionstore.common.useage.info4"));
			} else {
				map.put("message",
						MessageResourcesUtils.getMessage(request, "dailyoperattionstore.common.useage.info2"));
			}
			e.printStackTrace();
		} finally {
			try {
				response.getWriter().write(new Gson().toJson(map));
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 商户注册删除
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/dailyoperation/store/delete.web", method = RequestMethod.POST)
	public void delete(HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> map = new HashMap<String, Object>();
		String ids = request.getParameter("ids");
		StoreService storeService = (StoreService) IssTransactionContainer.getInstance(StoreService.class, true);
		try {
			if (StringUtils.isNotEmpty(ids)) {
				String[] idsStrings = ids.split(",");
				if (ids.length() != 0) {
					for (String id : idsStrings) {
						map = new HashMap<String, Object>();
						map.put("id", Long.parseLong(id));
						map.put("statusid", SysConstant.RecordStatus.INVALID);
						storeService.delete(map);
					}
					map.put("code", 200);
				}
			}
		} catch (ServiceException e) {
			map.put("code", 400);
			map.put("message", MessageResourcesUtils.getMessage(request, "dailyoperation.store.delect.exception"));
			e.printStackTrace();
		} catch (NumberFormatException e) {
			map.put("code", 400);
			map.put("message", MessageResourcesUtils.getMessage(request, "dailyoperation.store.delect.exception"));
			e.printStackTrace();
		} finally {
			try {
				response.getWriter().write(new Gson().toJson(map));
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}

	/**
	 * 跳转到修改的页面 商户管理修改
	 * 
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/dailyoperation/store/findOne", method = RequestMethod.GET)
	public String findOne(HttpServletRequest request, Model model) {
		String id = request.getParameter("id");
		StoreService storeService = (StoreService) IssTransactionContainer.getInstance(StoreService.class, false);
		if (StringUtils.isNotEmpty(id)) {
			StoreEntity entity = storeService.findOne(Long.parseLong(id));
			model.addAttribute("store", entity);
			model.addAttribute("number", entity == null ? "" : entity.getNumber());
			if (entity != null && entity.getBusinesslicenseid() != null) {
				AttachmentService attachmentService = (AttachmentService) IssTransactionContainer
						.getInstance(AttachmentService.class, false);
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("id", entity.getBusinesslicenseid());
				map.put("statusid", SysConstant.RecordStatus.VALID);
				Attachment attachment = attachmentService.findOneAttachmentByMap(map);
				attachment.setName(attachment.getName() + "." + attachment.getSuffix());
				model.addAttribute("attachment", attachment);
			}
		}
		List<Province> provinces = storeService.selectProvinceList();
		model.addAttribute("provinces", provinces);
		return "/WEB-INF/jsp/dailyoperation/store/storeManageUpdate";
	}

	/**
	 * 复核列表，得到列表数据
	 *
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/dailyoperation/store/getApproveJson.json", method = { RequestMethod.GET,
			RequestMethod.POST })
	public void getApproveJson(HttpServletRequest request, HttpServletResponse response) {
		try {
			PangingParam pangingParam = (PangingParam) ServletUtils.getParametersToBaseEntity(request, PangingParam.class);
			Map<String, Object> map = new HashMap<String, Object>();
			map = ServletUtils.getParametersToHashMap(request);
			DataGrid dataGrid = new DataGrid();
			dataGrid.setPangingParam(pangingParam);
			map.put("startrow", dataGrid.getStartrow());
			map.put("endrow", dataGrid.getRows());
			map.put("sort", dataGrid.getSort());
			map.put("apply", true);
			map.put("modifyuserid", getUserContext().getLoginUser().getId());
			String name = request.getParameter("name");
			if (StringUtils.isNotEmpty(name)) {
				map.put("name", name.trim());
			}
			String state = request.getParameter("state");
			String flag = request.getParameter("flag");
			if (StringUtils.isNotEmpty(flag) && !StringUtils.equals(flag, "undefined")) {
				if (StringUtils.isNotEmpty(state) && !StringUtils.equals(state, "undefined")) {
					map.put("state", Long.parseLong(state));
				} else {
					map.put("state", SysConstant.CommonApproveStatus.SUBMITTED);
				}
			} else {
				map.put("state", SysConstant.CommonApproveStatus.SUBMITTED);
			}
			map.put("order", dataGrid.getOrder());
			DataResult dataResult = getDataResult(pangingParam, map);
			if (pangingParam.getReportExportType() == 0) {
				response.getWriter().write(JSONFactory.toJSONString(dataResult, userContext));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@RequestMapping(value = "/dailyoperation/store/getCityJson.json", method = RequestMethod.GET)
	public void getCityJson(HttpServletResponse response, HttpServletRequest request) {
		List<City> list = new ArrayList<City>();
		StoreService storeService = (StoreService) IssTransactionContainer.getInstance(StoreService.class, false);
		try {
			String provinceid = request.getParameter("id");
			if (StringUtils.isNotEmpty(provinceid)) {
				list = storeService.selectCityByProvinceId(Long.parseLong(provinceid));
			}
		} catch (ServiceException e) {
			e.printStackTrace();
		} catch (NumberFormatException e) {
			e.printStackTrace();
		} finally {
			try {
				response.getWriter().write(new Gson().toJson(list));
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 获得一个 DataResult对象
	 *
	 * @param pangingParam
	 * @param map
	 * @return
	 */
	private DataResult getDataResult(PangingParam pangingParam, Map<String, Object> map) {
		map.put("statusid", SysConstant.RecordStatus.VALID);
		map.put("storesources", SysConstant.StoreSources.STORE);
		StoreService storeService = (StoreService) IssTransactionContainer.getInstance(StoreService.class, false);
		long resultCount = storeService.findResultCount(map);
		List<StoreEntity> resultList = storeService.findResultList(map);
		DataStyle dataStyle = new DataStyle();
		dataStyle.setPageIndex(pangingParam.getPage());
		dataStyle.setDataCount(resultCount);
		dataStyle.setDataList(resultList);
		dataStyle.addDepict("modifytime", DataTypeConstant.DATETIME);
		dataStyle.addDepict("number", DataTypeConstant.STRING);
		dataStyle.addDepict("name", DataTypeConstant.STRING);
		dataStyle.addDepict("corporate", DataTypeConstant.STRING);
		dataStyle.addDepictByDataDictionary("population", DictTypeConstant.POPULATION);
		dataStyle.addDepict("cityid", DataTypeConstant.LONG);
		dataStyle.addDepict("provinceid", DataTypeConstant.LONG);
		dataStyle.addDepictByDataDictionary("industry", DictTypeConstant.STOREINDUSTRY);
		dataStyle.addDepictByDataDictionary("quality", DictTypeConstant.QUALITY);
		dataStyle.addDepict("realname", DataTypeConstant.STRING);
		dataStyle.addDepict("description", DataTypeConstant.STRING);
		dataStyle.addDepict("email", DataTypeConstant.STRING);

		dataStyle.addDepict("businesslicensecode", DataTypeConstant.STRING);
		dataStyle.addDepict("organizationcode", DataTypeConstant.STRING);
		dataStyle.addDepict("certificatecode", DataTypeConstant.STRING);

		dataStyle.addDepict("telephonenumber", DataTypeConstant.STRING);
		dataStyle.addDepict("phonenumber", DataTypeConstant.STRING);
		dataStyle.addDepictByFunction("state", SysConstant.CommonApproveStatus.class, "getStateName", new Class[] { long.class });
		dataStyle.addDepictByFunction("statusid", SysConstant.RecordStatus.class, "getName", new Class[] { long.class });
		dataStyle.addDepictByFunction("businessstatus", SysConstant.CommonUsedStatus.class, "getName", new Class[] { long.class });
		dataStyle.addDepict("id", DataTypeConstant.LONG);
		DataResult dataResult = PangingTools.buildResultPagerInfo(dataStyle);
		return dataResult;
	}

	@RequestMapping(value = "/dailyoperation/store/getManageJson.json", method = { RequestMethod.GET,
			RequestMethod.POST })
	public void getManageJson(HttpServletRequest request, HttpServletResponse response) {
		try {
			PangingParam pangingParam = (PangingParam) ServletUtils.getParametersToBaseEntity(request, PangingParam.class);
			Map<String, Object> map = new HashMap<String, Object>();
			map = ServletUtils.getParametersToHashMap(request);
			DataGrid dataGrid = new DataGrid();
			dataGrid.setPangingParam(pangingParam);
			map.put("startrow", dataGrid.getStartrow());
			map.put("endrow", dataGrid.getRows());
			map.put("sort", dataGrid.getSort());
			String name = request.getParameter("name");
			if (StringUtils.isNotEmpty(name)) {
				map.put("name", name.trim());
			}
			String state = request.getParameter("state");
			String flag = request.getParameter("flag");
			if (StringUtils.isNotEmpty(flag) && !StringUtils.equals(flag, "undefined")) {
				if (StringUtils.isNotEmpty(state) && !StringUtils.equals(state, "undefined")) {
					map.put("state", Long.parseLong(state));
				} else {
					map.put("state", SysConstant.CommonApproveStatus.OK);
					// map.put("state", null);
				}
			} else {
				map.put("state", SysConstant.CommonApproveStatus.OK);
			}
			map.put("order", dataGrid.getOrder());
			DataResult dataResult = getDataResult(pangingParam, map);
			if (pangingParam.getReportExportType() == 0) {
				response.getWriter().write(JSONFactory.toJSONString(dataResult, userContext));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public String getName(String dictType, String code) {
		DataDictionaryInfo dataDictionaryInfo = DataDictionaryManage.getDataDictionaryInfo(dictType, code);
		String name = "";
		if (dataDictionaryInfo != null) {
			name = dataDictionaryInfo.getDictName();
		}
		return name;
	}

	/**
	 * 获得注册页面信息的列表，得到注册商户的列表数据
	 *
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/dailyoperation/store/getStoreListJson.json", method = { RequestMethod.GET,
			RequestMethod.POST })
	public void getStoreListJson(HttpServletRequest request, HttpServletResponse response) {
		try {
			PangingParam pangingParam = (PangingParam) ServletUtils.getParametersToBaseEntity(request, PangingParam.class);
			Map<String, Object> map = new HashMap<String, Object>();
			map = ServletUtils.getParametersToHashMap(request);
			DataGrid dataGrid = new DataGrid();
			dataGrid.setPangingParam(pangingParam);
			map.put("startrow", dataGrid.getStartrow());
			map.put("endrow", dataGrid.getRows());
			map.put("sort", dataGrid.getSort());
			String name = request.getParameter("name");
			if (StringUtils.isNotEmpty(name)) {
				map.put("name", name.trim());
			}
			String state = request.getParameter("state");
			if (StringUtils.isNotEmpty(state)) {
				map.put("state", Long.parseLong(state));
			}
			map.put("order", dataGrid.getOrder());
			DataResult dataResult = getDataResult(pangingParam, map);
			if (pangingParam.getReportExportType() == 0) {
				response.getWriter().write(JSONFactory.toJSONString(dataResult, userContext));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private SystemEmail getSystemEmail() {
		Map<String, Object> paramsMap = new HashMap<String, Object>();
		paramsMap.put("used", SysConstant.CommonUsedStatus.START);
		paramsMap.put("statusid", SysConstant.RecordStatus.VALID);
		paramsMap.put("templatetype", SysConstant.TemplateEmailType.APPROVALSTORE);
		SystemEmailService emailService = (SystemEmailService) IssTransactionContainer.getInstance(SystemEmailService.class, false);
		SystemEmail systemEmail = emailService.queryEmailSetByMap(paramsMap);
		return systemEmail;
	}

	/**
	 * 商户复核通过初始化商户用户 edit by yoyo 复核初始化方法 1、初始商户用户 2、将商户信息保存至redis
	 *
	 * @param flag
	 *            是否开启事务
	 * @return
	 */
	private void initialization(Long storeId) {
		// 1、初始用户
		StoreService storeService = (StoreService) IssTransactionContainer.getInstance(StoreService.class, true);
		StoreEntity entity = storeService.findOne(storeId);
		try {
			// 有效结束日期为开始日期后5年
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(new Date());
			calendar.add(Calendar.YEAR, 10);
			String password = RSAUtils.getRandomString(8);
			AdminUser user = new AdminUser();
			user.setStoreid(storeId);
			String passwordSHA = CommonCrypto.encryptSHAEncoder(password);
			user.setPassword(passwordSHA);
			user.setValidstart(new Date());
			user.setValidend(calendar.getTime());
			user.setInputtime(new Date());
			user.setInputuserid(userContext.getLoginUser().getId());
			user.setModifytime(new Date());
			user.setModifyuserid(userContext.getLoginUser().getId());
			user.setStatusid(SysConstant.RecordStatus.VALID);
			StoreLoginUser tmp = null;
			SystemEmail systemEmail = getSystemEmail();
			Map<String, String> emailMap = new HashMap<String, String>();
			emailMap.put("storeName", entity.getName());
			String content = "";
			for (int i = 1; i < 3; i++) {
				String loginname = "ad" + storeId + i + "@" + entity.getWebsite();
				user.setLoginname(loginname);
				tmp = (StoreLoginUser) JedisUtil.getPublicDataObject(user.getLoginname(), StoreLoginUser.class, JedisUtil.STORE_LOGINUSER);
				if (tmp == null) {
					content += "第" + i + "个用户名：" + loginname + ",密码：" + password + ",";
					storeService.insert(user);
					tmp = new StoreLoginUser();
					tmp.setId(user.getId());
					tmp.setStoreid(user.getStoreid());
					tmp.setLoginname(loginname);
					tmp.setPassword(passwordSHA);
					tmp.setValidstart(user.getValidstart());
					tmp.setValidend(user.getValidend());
					tmp.setPwdchangedate(user.getPwdchangedate());
					tmp.setCanLogin(SysConstant.YesOrNo.YES);
					tmp.setUsertype(SysConstant.StoreUserType.ADMIN);
					tmp.setUsername(user.getLoginname());
					JedisUtil.insertPublicDataObject(loginname, tmp, JedisUtil.STORE_LOGINUSER);
				} else {
					continue;
				}
			}
			if (StringUtils.isNotEmpty(content)) {
				content = content.substring(0, content.length() - 1);
			}
			try {
				emailMap.put("userInfo", content);
				content = FreeMarkerResolve.freemarkerProcess(emailMap, systemEmail.getTemplatecontent());
				Map<String, Object> messageMap = new HashMap<String, Object>();
				messageMap.put("content", content);
				messageMap.put("email", entity.getEmail());
				messageMap.put("subject", systemEmail.getSubject());
				storeService.sendEmailData(messageMap);
			} catch (Exception e) {
				e.printStackTrace();
			}
			// 2、将商户信息保存至redis

			syncStroeInfoToRedis(storeId);

			// 3、未挂接的商户，自动匹配一个数据源
			DatabaseBindingService bindingService = (DatabaseBindingService) IssTransactionContainer
					.getInstance(DatabaseBindingService.class, true);
			List<DatabaseBinding> list = bindingService.getBindingListByStoreid(storeId);
			if (list == null || list.size() == 0) {
				DatabaseResource resource = new DatabaseResource();
				resource.setStatusid(SysConstant.RecordStatus.VALID);
				resource = bindingService.nextBindingResource(resource);
				if (resource != null) {
					bindingService.addDatabaseBinding(storeId.toString(), resource);
				}
			}

			// 4、将商户数据源信息同步redis
			StoreDatabaseResourceService storeDatabaseResourceService = (StoreDatabaseResourceService) IssTransactionContainer
					.getInstance(StoreDatabaseResourceService.class, false);
			Map<String, Long> query = new HashMap<String, Long>();
			query.put("statusid", SysConstant.RecordStatus.VALID);
			query.put("storeid", storeId);
			List<RouteInfo> storeRouteList = storeDatabaseResourceService.queryStoreDatabaseByStoreID(query);
			if (storeRouteList != null && storeRouteList.size() > 0) {
				RouteInfo routeInfo = storeRouteList.get(0);
				JedisUtil.insertObject(routeInfo.getStoreid().toString(), routeInfo,
						JedisUtil.CONT_CLUSTERNAME_USERROUTE);
			}
		} catch (ServiceException e) {
			e.printStackTrace();
		}

	}

	/**
	 * 跳转到注册商户的页面
	 *
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/dailyoperation/store/intoStoreInfo.web", method = RequestMethod.GET)
	public String intoStoreInfo(Model model) {
		StoreService storeService = (StoreService) IssTransactionContainer.getInstance(StoreService.class, false);
		Integer num = storeService.queryMaxNumber();
		String number = "S" + new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()) + num;
		model.addAttribute("number", number);
		List<Province> provinces = storeService.selectProvinceList();
		model.addAttribute("provinces", provinces);
		return "/WEB-INF/jsp/dailyoperation/store/storeAdd";
	}

	/**
	 * 跳转到注册商户的列表页面
	 *
	 * @return
	 */
	@RequestMapping(value = "/dailyoperation/store/list.web", method = RequestMethod.GET)
	public String list() {
		return "/WEB-INF/jsp/dailyoperation/store/storeList";
	}

	@RequestMapping(value = "/dailyoperation/store/manageList.web", method = RequestMethod.GET)
	public String manageList() {
		return "/WEB-INF/jsp/dailyoperation/store/storeManage";
	}

	/**
	 * @描述：查询商户信息编号是否存在
	 * @author HUANGYUAN
	 * @TIME:2015年9月29日 上午9:42:13
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/dailyoperation/store/queryStoreInfoNumber.json", method = RequestMethod.POST)
	public void queryStoreInfoNumber(HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			StoreService storeService = (StoreService) IssTransactionContainer.getInstance(StoreService.class, false);
			String name = request.getParameter("name");
			String id = request.getParameter("id");
			map.put("name", name);
			map.put("id", id);
			map.put("statusid", SysConstant.RecordStatus.VALID);
			Long number = storeService.queryStoreInfoNumber(map);
			if (StringUtils.isNotEmpty(id)) {
				StoreEntity store = storeService.queryStoreById(map);
				if (store != null) {
					if (!StringUtils.equals(name, store.getName())) {
						if (number > 0) {
							map.put("code", true);
							map.put("message", MessageResourcesUtils.getMessage(request,
									"dailyoperation.store.name.validation.info"));
						}
					}
				}
			} else {
				if (number > 0) {
					map.put("code", true);
					map.put("message",
							MessageResourcesUtils.getMessage(request, "dailyoperation.store.name.validation.info"));
				}
			}
		} catch (ServiceException e) {
			e.printStackTrace();
		} finally {
			try {
				response.getWriter().write(new Gson().toJson(map));
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 跳转到商户审核的页面
	 *
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/dailyoperation/store/storeApprovalEdit.web", method = RequestMethod.GET)
	public String storeApprovalEdit(HttpServletRequest request, Model model) {
		String id = request.getParameter("id");
		StoreService storeService = (StoreService) IssTransactionContainer.getInstance(StoreService.class, false);
		if (StringUtils.isNotEmpty(id)) {
			StoreEntity entity = storeService.findOne(Long.parseLong(id));
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("cityid", entity.getCityid());
			map.put("pid", entity.getProvinceid());
			map = storeService.getCityName(map);
			if (map != null) {
				entity.setAddress(map.get("provincename").toString() + " " + map.get("cityname"));
			}
			entity.setQualityStr(getName(DictTypeConstant.QUALITY, entity.getQuality()));
			entity.setPopulationStr(getName(DictTypeConstant.POPULATION, entity.getPopulation()));
			entity.setIndustryStr(getName(DictTypeConstant.STOREINDUSTRY, entity.getIndustry()));
			model.addAttribute("store", entity);
		}
		String isApprove = request.getParameter("isApprove");
		if (StringUtils.isNotEmpty(isApprove)) {
			model.addAttribute("flag", 1);// 判断是否显示审核按钮

		}
		return "/WEB-INF/jsp/dailyoperation/store/storeApprovalEdit";
	}

	/**
	 * 商户注册修改
	 * 
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/dailyoperation/store/storeEdit.web", method = RequestMethod.GET)
	public String storeEdit(HttpServletRequest request, Model model) {
		String id = request.getParameter("id");
		StoreService storeService = (StoreService) IssTransactionContainer.getInstance(StoreService.class, false);
		if (StringUtils.isNotEmpty(id)) {
			StoreEntity entity = storeService.findOne(Long.parseLong(id));
			if (entity != null && entity.getBusinesslicenseid() != null) {
				AttachmentService attachmentService = (AttachmentService) IssTransactionContainer
						.getInstance(AttachmentService.class, false);
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("id", entity.getBusinesslicenseid());
				map.put("statusid", SysConstant.RecordStatus.VALID);
				Attachment attachment = attachmentService.findOneAttachmentByMap(map);
				if (attachment != null) {
					attachment.setName(attachment.getName() + "." + attachment.getSuffix());
					model.addAttribute("attachment", attachment);
				}
			}
			model.addAttribute("store", entity);
			model.addAttribute("number", entity == null ? "" : entity.getNumber());
		}
		List<Province> provinces = storeService.selectProvinceList();
		model.addAttribute("provinces", provinces);
		return "/WEB-INF/jsp/dailyoperation/store/storeUpdate";
	}

	/**
	 * 信息保存
	 *
	 * @param request
	 * @param store
	 * @return
	 */
	@RequestMapping(value = "/dailyoperation/store/storeSave.web", method = RequestMethod.POST)
	public String storeSave(HttpServletRequest request, StoreEntity store, HttpServletResponse response) {
		Map<String, Object> map = new HashMap<String, Object>();
		StoreService storeService = (StoreService) IssTransactionContainer.getInstance(StoreService.class, true);
		try {
			// 判断flag=1为保存，flag=2 提交
			String flag = request.getParameter("flag");
			store.setInputuserid(userContext.getLoginUser().getId());
			store.setModifytime(new Date());
			store.setSources(SysConstant.StoreSources.MANAGER);
			store.setModifyuserid(userContext.getLoginUser().getId());
			if (StringUtils.isNotEmpty(flag)
					&& StringUtils.equals(flag, String.valueOf(SysConstant.CommonApproveStatus.SAVED))) {
				store.setState(SysConstant.CommonApproveStatus.SAVED);
				userContext.setInfoMessage(
						MessageResourcesUtils.getMessage(request, "dailyoperation.store.insert.success"));
			} else if (StringUtils.isNotEmpty(flag)
					&& StringUtils.equals(flag, String.valueOf(SysConstant.CommonApproveStatus.SUBMITTED))) {
				userContext.setInfoMessage(
						MessageResourcesUtils.getMessage(request, "dailyoperation.store.submit.success"));
				store.setState(SysConstant.CommonApproveStatus.SUBMITTED);
			} else {
				userContext.setInfoMessage(
						MessageResourcesUtils.getMessage(request, "dailyoperation.store.insert.success"));
				store.setState(SysConstant.CommonApproveStatus.SAVED);
			}
			store.setInputtime(new Date());
			store.setStatusid(SysConstant.RecordStatus.VALID);
			store.setBusinessstatus(SysConstant.CommonUsedStatus.STOP);
			storeService.insert(store);
			userContext.setCloseWindow(true);
		} catch (ServiceException e) {
			e.printStackTrace();
			map.put("message", MessageResourcesUtils.getMessage(request, "dailyoperation.store.insert.error"));
			map.put("code", 400);
		}
		return "/WEB-INF/jsp/dailyoperation/store/storeAdd";
	}

	/**
	 * 查看详情和审核的页面
	 *
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/dailyoperation/store/storeView.web", method = RequestMethod.GET)
	public String storeView(HttpServletRequest request, Model model) {
		String id = request.getParameter("id");
		StoreService storeService = (StoreService) IssTransactionContainer.getInstance(StoreService.class, false);
		if (StringUtils.isNotEmpty(id)) {
			StoreEntity entity = storeService.findOne(Long.parseLong(id));
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("cityid", entity.getCityid());
			map.put("pid", entity.getProvinceid());
			map = storeService.getCityName(map);
			if (map != null) {
				entity.setAddress(map.get("provincename").toString() + " " + map.get("cityname"));
			}
			entity.setQualityStr(getName(DictTypeConstant.QUALITY, entity.getQuality()));
			entity.setPopulationStr(getName(DictTypeConstant.POPULATION, entity.getPopulation()));
			entity.setIndustryStr(getName(DictTypeConstant.STOREINDUSTRY, entity.getIndustry()));
			model.addAttribute("store", entity);
			if (entity != null && entity.getBusinesslicenseid() != null) {
				AttachmentService attachmentService = (AttachmentService) IssTransactionContainer
						.getInstance(AttachmentService.class, false);
				map = new HashMap<String, Object>();
				map.put("id", entity.getBusinesslicenseid());
				map.put("statusid", SysConstant.RecordStatus.VALID);
				Attachment attachment = attachmentService.findOneAttachmentByMap(map);
				attachment.setName(attachment.getName() + "." + attachment.getSuffix());
				model.addAttribute("attachment", attachment);
			}
		}
		String isApprove = request.getParameter("isApprove");
		if (StringUtils.isNotEmpty(isApprove)) {
			model.addAttribute("flag", 1);// 判断是否显示审核按钮
		}
		model.addAttribute("approval", request.getParameter("approval"));
		return "/WEB-INF/jsp/dailyoperation/store/storeView";
	}

	private void syncStroeInfoToRedis(Long storeId) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("storeid", storeId);
		map.put("statusid", SysConstant.RecordStatus.VALID);
		StoreService storeService = (StoreService) IssTransactionContainer.getInstance(StoreService.class, true);
		List<StoreRedisInfo> list = storeService.findStoreRedisInfo(map);
		StoreRedisInfo storeInfo = (StoreRedisInfo) list.get(0);
		JedisUtil.insertPublicDataObject(storeInfo.getStoreid().toString(), storeInfo, JedisUtil.STORE_INFO);

	}

	/**
	 * @author HUANGYUAN
	 * @时间 2015年7月31日 下午4:19:07
	 * @param request
	 * @param store
	 * @param response
	 * @return
	 * @描述 修改商户的信息
	 */
	@RequestMapping(value = "/dailyoperation/store/updateStoreInfo.web", method = RequestMethod.POST)
	public void updateStoreInfo(HttpServletRequest request, StoreEntity store, HttpServletResponse response) {
		Map<String, Object> map = new HashMap<String, Object>();
		StoreService storeService = (StoreService) IssTransactionContainer.getInstance(StoreService.class, true);
		try {
			String id = request.getParameter("id");
			// 判断是否为提交
			String flag = request.getParameter("flag");
			store.setId(Long.parseLong(id));
			store.setInputuserid(userContext.getLoginUser().getId());
			store.setModifytime(new Date());
			store.setModifyuserid(userContext.getLoginUser().getId());
			if (StringUtils.isNotEmpty(flag)
					&& StringUtils.equals(flag, String.valueOf(SysConstant.CommonApproveStatus.SUBMITTED))) {
				store.setState(SysConstant.CommonApproveStatus.SUBMITTED);
				map.put("message", MessageResourcesUtils.getMessage(request, "dailyoperation.store.submit.success"));
			} else {
				map.put("message", MessageResourcesUtils.getMessage(request, "dailyoperation.store.insert.success"));
			}
			store.setModifyuserid(userContext.getLoginUser().getId());
			storeService.update(store);
			map.put("code", 200);
		} catch (ServiceException e) {
			map.put("message", MessageResourcesUtils.getMessage(request, "dailyoperation.store.insert.error"));
			map.put("code", 400);
			e.printStackTrace();
		} finally {
			try {
				response.getWriter().write(new Gson().toJson(map));
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	private MessageObject message = new MessageObject();
	private static SystemConfig systemConfig = new SystemConfig("interceptorFileType");

	/**
	 * @描述：附件的拷贝
	 * @author HUANGYUAN
	 * @TIME:2015年9月21日 下午4:07:22
	 * @param myfiles
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/dailyoperation/store/attachment/copy.web", method = { RequestMethod.POST,
			RequestMethod.GET })
	public void copy(MultipartHttpServletRequest request, HttpServletResponse response) {
		List<Attachment> attachments = new ArrayList<Attachment>();
		AttachmentService attachmentService = (AttachmentService) IssTransactionContainer
				.getInstance(AttachmentService.class, true);
		try {
			MongoDBManager manager = MongoDBManager.getDefaultMongoDBManager();
			Integer attachmentSize = manager.getFileMaxSize();
			Iterator<String> iterator = request.getFileNames();
			while (iterator.hasNext()) {
				MultipartFile multipartFile = request.getFile(iterator.next());
				String type = multipartFile.getContentType();
				String name = multipartFile.getOriginalFilename();
				float size = multipartFile.getSize() / (1024);
				Long filesize = Long.valueOf(attachmentSize) / 1024;
				Attachment attachment = new Attachment();
				String suffix = FileTools.getFileExtension(name);
				Map<String, Object> systemConfigMap = systemConfig.getKeyValueMap();
				if (FileTools.isVarabled(systemConfigMap, suffix)) {
					String errorMessage = MessageResourcesUtils.getMessage(request,
							"dailyoperation.store.website.alert7") + FileTools.getString(systemConfigMap);
					message.setErrorMessage(errorMessage);
					break;
				} else {
					InputStream stream = multipartFile.getInputStream();
					if (FileTools.isVarabled(systemConfigMap, FileTools.getInterceptorFileType(stream))) {
						String errorMessage = MessageResourcesUtils.getMessage(request,
								"dailyoperation.store.website.alert7") + FileTools.getString(systemConfigMap);
						message.setErrorMessage(errorMessage);
						break;
					}
				}
				String attSize = "";
				if (size < filesize) {
					if (size >= 1024 && size < 1024 * 1024) {
						attSize = (size / 1024) + "MB";
					} else if (filesize >= 1024 * 1024) {
						attSize = (size / 1024 / 1024) + "GB";
					} else if (size < 1) {
						attSize = size + "B";
					} else {
						attSize = size + "KB";
					}
					String attachmentfile = ServletUtils.uploadAttachmentfile(multipartFile.getInputStream(), manager,
							manager.getAttachmentDBName());
					attachment = new Attachment(name.substring(0, name.lastIndexOf(".")), attachmentfile, type, attSize,
							FileTools.getFileExtension(name));
					attachment.setInputtime(new Date());
					attachment.setModifytime(new Date());
					attachment.setStatusid(SysConstant.RecordStatus.VALID);
					attachment.setInputuserid(getUserContext().getLoginUser().getId());
					attachment.setModifyuserid(getUserContext().getLoginUser().getId());
					attachmentService.attachmentSave(attachment);
					System.out.println(attachment.getId());
					attachments.add(attachment);
					message.setObject(attachments);
					message.setInforMessage("文件符合要求...");
				} else {
					attSize = (filesize / 1024) + "MB";
					message.setInforMessage(null);
					message.setErrorMessage(
							name + MessageResourcesUtils.getMessage(request, "topic.poster.status.alert7") + attSize);
					break;
				}
			}
		} catch (Exception e) {
			logger.debug(e.getMessage());
			e.printStackTrace();
			message.setErrorMessage(MessageResourcesUtils.getMessage(request, "dailyoperation.store.website.alert6"));
		} finally {
			try {
				response.getWriter().write(message.getJsonMapper(message));
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 校验该网址的商户是否存在或者该网站是否存在
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/dailyoperation/store/validationWebSite.json", method = { RequestMethod.GET })
	public void validationWebSite(HttpServletRequest request, HttpServletResponse response) {
		MessageObject message = new MessageObject();
		String webSite = request.getParameter("website");
		String id = request.getParameter("id");
		StoreService service = (StoreService) IssTransactionContainer.getInstance(StoreService.class, false);
		try {
			if (StringUtils.isNotEmpty(webSite)) {
				long count = service.queryStoreByWebSite(webSite);
				if (count > 0) {
					if (StringUtils.isNotEmpty(id)) {
						StoreEntity entity = service.findOne(Long.parseLong(id));
						if (entity != null && webSite.equals(entity.getWebsite())) {
							message.setInforMessage(
									MessageResourcesUtils.getMessage(request, "dailyoperation.store.website.alert3"));
						}
					} else {
						message.setErrorMessage(
								MessageResourcesUtils.getMessage(request, "dailyoperation.store.website.alert4"));
					}
				} else {
					message.setInforMessage(
							MessageResourcesUtils.getMessage(request, "dailyoperation.store.website.alert3"));
				}
			} else {
				String errorMessage = MessageResourcesUtils.getMessage(request, "dailyoperation.store.website.alert5");
				message.setErrorMessage(errorMessage);
			}
		} catch (Exception e) {
			String errorMessage = MessageResourcesUtils.getMessage(request, "dailyoperation.store.website.alert5");
			message.setErrorMessage(errorMessage);
			e.printStackTrace();
		} finally {
			try {
				// 这句话的意思，是让浏览器用utf8来解析返回的数据
				response.setHeader("Content-type", "text/html;charset=UTF-8");
				response.getWriter().write(message.getJsonMapper(message));
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	@RequestMapping(value = "/dailyoperation/store/resetSendEmail.json", method = RequestMethod.GET)
	public void resetSendEmail(HttpServletRequest request, HttpServletResponse response) {
		String storeids = request.getParameter("ids");
		MessageObject message = new MessageObject();
		try {
			if (StringUtils.isNotEmpty(storeids)) {
				String[] ids = storeids.split(",");
				for (String id : ids) {
					try {
						Long storeId = Long.parseLong(id);
						StoreService storeService = (StoreService) IssTransactionContainer
								.getInstance(StoreService.class, false);
						List<AdminUser> adminUsers = storeService.queryAdminUserList(storeId);
						initializationUpdateAdminUser(storeId, adminUsers);
						String inforMessage = MessageResourcesUtils.getMessage(request, "alertinfo.user.jsp.alert18");
						message.setInforMessage(inforMessage);
					} catch (NumberFormatException e) {
						e.printStackTrace();
						String errorMessage = MessageResourcesUtils.getMessage(request, "alertinfo.user.jsp.alert19");
						message.setErrorMessage(errorMessage);
						break;
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			String errorMessage = MessageResourcesUtils.getMessage(request, "alertinfo.user.jsp.alert19");
			message.setErrorMessage(errorMessage);
		} finally {
			try {
				response.getWriter().write(message.getJsonMapper(message));
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	private void initializationUpdateAdminUser(Long storeId, List<AdminUser> adminUsers) {
		// 1、初始用户
		StoreService storeService = (StoreService) IssTransactionContainer.getInstance(StoreService.class, true);
		StoreEntity entity = storeService.findOne(storeId);
		try {
			String password = RSAUtils.getRandomString(8);
			String passwordSHA = CommonCrypto.encryptSHAEncoder(password);
			SystemEmail systemEmail = getSystemEmail();
			Map<String, String> emailMap = new HashMap<String, String>();
			emailMap.put("storeName", entity.getName());
			String content = "";
			int num = 1;
			AdminUser adminUser = new AdminUser();
			for (Iterator<AdminUser> iterator = adminUsers.iterator(); iterator.hasNext();) {
				AdminUser user = (AdminUser) iterator.next();
				user.setPassword(passwordSHA);
				user.setModifytime(new Date());
				user.setModifyuserid(userContext.getLoginUser().getId());
				user.setStatusid(SysConstant.RecordStatus.VALID);
				content += "第" + num + "个用户名：" + user.getLoginname() + ",密码：" + password
						+ ",";
				StoreLoginUser tmp = (StoreLoginUser) JedisUtil.getPublicDataObject(user.getLoginname(),
						StoreLoginUser.class, JedisUtil.STORE_LOGINUSER);
				if (tmp == null) {
					tmp = new StoreLoginUser();
					tmp.setId(user.getId());
					tmp.setStoreid(user.getStoreid());
					tmp.setLoginname(user.getLoginname());
					tmp.setPassword(passwordSHA);
					tmp.setValidstart(user.getValidstart());
					tmp.setValidend(user.getValidend());
					tmp.setPwdchangedate(user.getPwdchangedate());
					tmp.setCanLogin(SysConstant.YesOrNo.YES);
					tmp.setUsertype(SysConstant.StoreUserType.ADMIN);
					tmp.setUsername(user.getLoginname());
					JedisUtil.insertPublicDataObject(user.getLoginname(), tmp, JedisUtil.STORE_LOGINUSER);
				} else {
					continue;
				}
				num++;
			}
			if (StringUtils.isNotEmpty(content)) {
				content = content.substring(0, content.length() - 1);
			}
			emailMap.put("userInfo", content);
			adminUser.setPassword(passwordSHA);
			adminUser.setStoreid(storeId);
			adminUser.setModifytime(new Date());
			adminUser.setModifyuserid(getUserContext().getLoginUser().getId());
			adminUser.setPwdchangedate(null);
			storeService.updateAdminUser(adminUser);
			content = FreeMarkerResolve.freemarkerProcess(emailMap, systemEmail.getTemplatecontent());
			Map<String, Object> messageMap = new HashMap<String, Object>();
			messageMap.put("content", content);
			messageMap.put("email", entity.getEmail());
			messageMap.put("subject", systemEmail.getSubject());
			storeService.sendEmailData(messageMap);
			// 2、将商户信息保存至redis
			syncStroeInfoToRedis(storeId);
			// 3、未挂接的商户，自动匹配一个数据源
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
	
	@RequestMapping(value = "/dailyoperation/store/attachment/download.json", method = RequestMethod.GET)
	public void download(HttpServletRequest request, HttpServletResponse response) {
		MongoDBManager manager = MongoDBManager.getDefaultMongoDBManager();
		String attachmentUrl = manager.getAttachmentUrl();
		String id = request.getParameter("id");
		AttachmentService attachmentService = (AttachmentService) IssTransactionContainer.getInstance(AttachmentService.class, false);
		try {
			if (StringUtils.isNotEmpty(id)) {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("id", id);
				Attachment attachment = attachmentService.findOneAttachmentByMap(map);
				String url = attachmentUrl + "/" + attachment.getMongofileame();
				byte[] bytes = FileTools.getInputStreamByNetUrl(url);
				// 清空response
				response.reset();
				// 设置response的Header
				String filename = attachment.getName() + "." + attachment.getSuffix();
				response.setHeader("Content-Disposition", "attachment; filename=" + java.net.URLEncoder.encode(filename, "UTF-8"));
				response.addHeader("Content-Length", "" + bytes.length);
				OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
				response.setContentType("application/octet-stream");
				toClient.write(bytes);
				toClient.flush();
				toClient.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
